package cn.kbyue.logdemo.config;

import cn.kbyue.logdemo.common.ThreadPoolExecutorMdcWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
public class ThreadTaskConfiguration {

    @Value("${spring.task.execution.pool.core-size}")
    public int corePoolSize;

    @Value("${spring.task.execution.pool.max-size}")
    public int maxPoolSize;

    @Value("${spring.task.execution.pool.queue-capacity}")
    public int queueCapacity;

    @Value("${spring.task.execution.pool.keep-alive}")
    public int keepAliveSeconds;

    @Value("${spring.task.execution.thread-name-prefix}")
    public String threadNamePrefix;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();

        pool.setCorePoolSize(corePoolSize);
        pool.setMaxPoolSize(maxPoolSize);
        // 队列容量,当核心线程数达到最大时，新任务会放在队列中排队等待执行
        pool.setQueueCapacity(queueCapacity);
        // 空闲线程回收期限
        pool.setKeepAliveSeconds(keepAliveSeconds);
        // 核心线程会一直存活，即使没有任务需要执行。（默认false）时，核心线程会超时关闭
        pool.setAllowCoreThreadTimeOut(false);
        //线程前缀名称
        pool.setThreadNamePrefix(threadNamePrefix);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        // 默认:AbortPolicy 丢弃任务，抛运行时异常
        // CallerRunsPolicy由调用线程处理该任务
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return pool;
    }

    @Bean("mdcExecutor")
    public ThreadPoolExecutor destroyImGroupTaskExecutor() {
        // 自定义 ThreadFactory 可以设置 线程分组 和 线程名称前缀
        ThreadPoolExecutor pool = new ThreadPoolExecutorMdcWrapper(corePoolSize, maxPoolSize, keepAliveSeconds, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(queueCapacity), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
        pool.allowCoreThreadTimeOut(false);
        return pool;
    }


    /**
     * 配置多个线程池
     */
    // @Bean("destroyResource")
    // public AsyncTaskExecutor destroyImGroupTaskExecutor() {
    //     return getAsyncTaskExecutor("del-resource-td-", maxPoolSize, queueCapacity);
    // }
    //
    // @Bean("statisticsData")
    // public AsyncTaskExecutor statisticsDataExecutor() {
    //     return getAsyncTaskExecutor("save-data-td-", maxPoolSize, queueCapacity);
    // }
    //
    // @Bean("commonTaskExecutor")
    // public AsyncTaskExecutor get() {
    //     return getAsyncTaskExecutor("common-ex-td-", maxPoolSize, queueCapacity);
    // }
    //
    // private AsyncTaskExecutor getAsyncTaskExecutor(String threadNamePrefix, int MAX_POOL_SIZE, int QUEUE_CAPACITY) {
    //     ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    //     taskExecutor.setCorePoolSize(corePoolSize);
    //     taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
    //     taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
    //     taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
    //     taskExecutor.setThreadNamePrefix(threadNamePrefix);
    //     taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //     return taskExecutor;
    // }

}
